// 运行时配置
import { LOGIN_PATH } from '@/constants';
import { RunTimeLayoutConfig, history } from '@umijs/max';
import { ConfigProvider, message } from 'antd';
import React from 'react';
import {
  CurrentUser,
  MenuItem,
  getCurrentUser,
  getMenuData,
} from './services/auth';

import HeadTitle from '@/components/HeadTitle';
import Menu from '@/components/Menu';
import { errorConfig } from './errorConfig';
import MyErrorBoundary from './layout/MyErrorBoundary';

console.log(process.env, 'process.env');
const Wrapper = ({ children }: any) => (
  <React.Suspense>{children}</React.Suspense>
);
// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<{
  currentUser?: CurrentUser;
  menuData?: MenuItem[];
  loading?: boolean;
  fetchUserInfo?: () => Promise<CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const currentUser = await getCurrentUser();
      return currentUser;
    } catch (error) {
      message.error('获取用户信息失败，请重试！');
      return undefined;
    }
  };

  // 获取菜单数据
  const fetchMenuData = async () => {
    try {
      const menuData = await getMenuData();
      const path = menuData[0]?.children[0]?.path;
      if (path) {
        history.push(path);
      }
      return menuData;
    } catch (error) {
      history.push(LOGIN_PATH);
      message.error('获取菜单数据失败，请重试！');
      return [];
    }
  };

  // 如果不是登录页面，获取用户信息
  const currentUser = await fetchUserInfo();
  const menuData = await fetchMenuData();

  return {
    currentUser,
    menuData,
    fetchUserInfo,
  };
}

let extraMenu: any = [];
export async function render(oldRender: () => void) {
  const menuData = await getMenuData();
  extraMenu = menuData;
  oldRender();
}

export async function patchClientRoutes({ routes }: any) {
  const pitchRoute = (route) => {
    console.log(route, pitchRoute);
    const result = route.map((item) => {
      if (item.children && item.children.length > 0) {
        return {
          path: item.path,
          label: item.name,
          // icon: <item.icon />,
          children: pitchRoute(item.children),
        };
      } else {
        console.log(item.path);
        const Component = React.lazy(() => import(`@/pages${item.path}/index`));
        const wrapperComponent = (
          <Wrapper>
            <Component />
          </Wrapper>
        );
        return {
          path: item.path,
          label: item.name,
          // icon: <item.icon />,
          element: wrapperComponent,
        };
      }
    });
    return result;
  };

  if (extraMenu.length > 0) {
    const route = pitchRoute(extraMenu);
    console.log(route, 'route', routes);
    route.forEach((item: any) => {
      routes[routes.length - 1].routes.unshift(item);
    });
  }
}

export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    title: '电商后台',
    layout: 'mix',
    ErrorBoundary: MyErrorBoundary,
    menu: {
      // locale: false,
      // 使用从服务端获取的菜单数据
      params: initialState,
      request: async (params, defaultMenuData) => {
        return defaultMenuData;
      },
    },
    menuRender: (props) => {
      if (!props.menuData) return null;
      const menu = props.menuData;
      menu?.pop();
      menu.reverse();
      const menuData = props.menuData;

      // return <Menu mode="inline" style={{ width: 256 }} onClick={(e) => handleMenuClick(e)} items={menuData} />;
      return <Menu initialState={initialState} menuData={menuData} />;
    },
    // 水印设置
    // waterMarkProps: {
    //   content: initialState?.currentUser?.name,
    // },
    headerTitleRender: (props) => {
      console.log(props);
      return HeadTitle();
    },
    menuHeaderRender: false,
    // 页面加载时的loading效果
    childrenRender: (children) => {
      return children;
    },
    // 自定义头部右侧内容
    headerContentRender: () => {
      return <div>headerContentRender</div>;
    },
    rightContentRender: () => <div>rightContentRender</div>,
    // 自定义页脚
    footerRender: () => null,
  };
};

export function rootContainer(container: any) {
  console.log('rootContainer', container);
  return (
    <ConfigProvider
      theme={{
        token: {
          colorLink: process.env.primaryColor,
          colorError: '#FA4616',
          colorPrimary: process.env.primaryColor,
          colorTextPlaceholder: '#CCCCCC',
          colorText: '#2a2b2e',
          borderRadius: 4,
        },
        components: {
          Input: {
            colorBorder: '#e1e1e8',
          },
          Table: {
            headerBg: 'rgb(244,246,250)',
          },
        },
      }}
    >
      {container}
    </ConfigProvider>
  );
}

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...errorConfig,
};
